package com.xxxx.server.controller;

import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.WebMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.security.Principal;
import java.time.LocalDateTime;

/**
 * @Author Lionel
 * @Date 2020/10/20 20:45
 * Created by IntelliJ IDEA 2020.1.
 * Project: yeb
 * Description：消息控制层
 */
@Controller
public class WsController {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void sendMsg(Authentication authentication, WebMessage webMessage){
        //获取Admin对象
        Admin admin = (Admin) authentication.getPrincipal();
        //设置消息相关属性
        webMessage.setFrom(admin.getUsername());
        webMessage.setFormNickName(admin.getName());
        webMessage.setDate(LocalDateTime.now());
        //发送消息给指定用户
        simpMessagingTemplate.convertAndSendToUser(webMessage.getTo(),"/queue/chat",webMessage);
    }
}
